<template>
  <div class="user-table-page">
    <!-- 顶部“新增用户”按钮 -->
    <div class="top-view">
      <span class="data-storage">资源列表</span>
      <div class="two-btn">
        <button class="btn-base fst-btn" @click="handleAdd">新增</button>
        <button class="btn-base scd-btn" @click="handleEdit">编辑</button>
      </div>
    </div>

    <!-- 调用自定义表格组件 -->
    <ElTable
      :data="currentPageData"
      :columns="tableColumnsRef"
      show-selection
      show-pagination
      :pagination="paginationRef"
      @selection-change="handleSelect"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 姓名列：自定义头像 + 文字 -->
      <template #name="{ row }">
        <div class="name-cell">
          <span>{{ row.name }}</span>
        </div>
      </template>

      <!-- 状态列 -->
      <template #status="{ row }">
        <span class="status-text">{{ row.status }}</span>
      </template>

      <!-- 操作列 -->
      <template #operation="{ row }">
        <div class="operation-cell">
          <el-button type="primary" link @click="handleEditRow(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDeleteRow(row)">删除</el-button>
        </div>
      </template>
    </ElTable>

    <!-- 资源弹窗 -->
    <ResourceModal
      :visible="modalVisible"
      :resource-data="currentResource"
      @update:visible="modalVisible = $event"
      @confirm="handleModalConfirm"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
// 1. 导入自定义表格组件
import ElTable from '@/components/Table/ElTable.vue';
// 2. 从抽离的 JS 文件中导入数据，重命名导入的变量
import { tableColumns as originTableColumns, initPagination as originPagination } from '../index';
// 3. 导入API
import { getDashboardResources, createResource, updateResource, deleteResource } from '@/api/dashboard';
// 4. 导入资源弹窗组件
import ResourceModal from './ResourceModal.vue';

const tableColumnsRef = ref(originTableColumns);
const paginationRef = ref({ ...originPagination });
const userListRef = ref([]);

// 弹窗相关
const modalVisible = ref(false);
const currentResource = ref({});
const selectedRows = ref([]);

// 添加操作列到表格
const tableColumnsWithOperation = [...originTableColumns,
  { prop: 'operation', label: '操作', width: 150, align: 'center', slotName: 'operation' }
];
tableColumnsRef.value = tableColumnsWithOperation;

// 计算当前页数据
const currentPageData = computed(() => {
  const startIndex = (paginationRef.value.currentPage - 1) * paginationRef.value.pageSize;
  const endIndex = startIndex + paginationRef.value.pageSize;
  return userListRef.value.slice(startIndex, endIndex);
});

// 获取资源列表数据
const fetchResources = async (page = 1, pageSize = 8) => {
  try {
    const response = await getDashboardResources({ page, pageSize });
    if (response.code === 200) {
      userListRef.value = response.data.list;
      paginationRef.value.total = response.data.pagination.total;
      paginationRef.value.currentPage = response.data.pagination.currentPage;
      paginationRef.value.pageSize = response.data.pagination.pageSize;
    }
  } catch (error) {
    console.error('获取资源列表失败:', error);
  }
};

// 勾选事件
const handleSelect = (rows) => {
  selectedRows.value = rows;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  paginationRef.value.pageSize = val;
  paginationRef.value.currentPage = 1; // 重置到第一页
  fetchResources(1, val);
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  paginationRef.value.currentPage = val;
  fetchResources(val, paginationRef.value.pageSize);
};

// 新增资源
const handleAdd = () => {
  currentResource.value = {};
  modalVisible.value = true;
};

// 编辑资源（批量）
const handleEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条数据进行编辑');
    return;
  }
  currentResource.value = { ...selectedRows.value[0] };
  modalVisible.value = true;
};

// 编辑资源（单行）
const handleEditRow = (row) => {
  currentResource.value = { ...row };
  modalVisible.value = true;
};

// 删除资源
const handleDeleteRow = async (row) => {
  try {
    await deleteResource(row.id);
    ElMessage.success('删除成功');
    // 重新获取数据
    fetchResources(paginationRef.value.currentPage, paginationRef.value.pageSize);
  } catch (error) {
    ElMessage.error('删除失败');
    console.error('删除资源失败:', error);
  }
};

// 弹窗确认
const handleModalConfirm = async (data) => {
  try {
    if (data.id) {
      // 更新资源
      await updateResource(data.id, data);
      ElMessage.success('更新成功');
    } else {
      // 创建资源
      await createResource(data);
      ElMessage.success('创建成功');
    }
    // 关闭弹窗
    modalVisible.value = false;
    // 重新获取数据
    fetchResources(paginationRef.value.currentPage, paginationRef.value.pageSize);
  } catch (error) {
    ElMessage.error(data.id ? '更新失败' : '创建失败');
    console.error('保存资源失败:', error);
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchResources();
});

// 编辑事件
// const handleEdit = (row) => {
//   console.log('编辑行：', row);
// };

// 删除事件（响应式更新 userList 和 pagination.total）
// const handleDelete = (row) => {
//   console.log('删除行：', row);
//   const index = userListRef.value.findIndex(item => item.id === row.id);
//   if (index !== -1) {
//     userListRef.value.splice(index, 1);
//     paginationRef.value.total = userListRef.value.length; // 更新总条数
//     // 若当前页无数据且不是第一页，页码减一
//     if (currentPageData.value.length === 0 && paginationRef.value.currentPage > 1) {
//       paginationRef.value.currentPage--;
//     }
//   }
// };

// // 新增事件
// const handleAddUser = () => {
//   console.log('打开新增用户弹窗');
//   // 模拟新增（实际需调用接口）
//   const newUser = {
//     id: userListRef.value.length + 1,
//     name: '新增用户',
//     account: '20234567890',
//     amount: '5000',
//     role: '2023-168002',
//     status: '主账号',
//     avatar: 'https://via.placeholder.com/40?text=新'
//   };
// userListRef.value.unshift(newUser);
// paginationRef.value.total = userListRef.value.length; // 更新总条数
// };
</script>
<style scoped lang="scss">
.user-table-page {
  border-radius: 10px;

  .add-user-btn {
    margin-bottom: 5px;

  }

  .name-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #409eff;

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
    }
  }

  .top-view {
    background-color: rgb(253, 253, 251);
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .data-storage {
      font-weight: 600;
    }

    .two-btn {
      display: flex;
      justify-content: flex-end;

      .scd-btn {
        margin-left: 8px;

      }

    }
  }

  .el-table {
    .el-button {
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .el-pagination {
    margin-top: 20px;

    .el-pager {
      li {
        min-width: 32px;
        height: 32px;
        line-height: 32px;
      }
    }
  }
}
</style>
